/
DateTimeIterator.php
119 lines (92 loc) 路 2.63 KB
/
DateTimeIterator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
declare(strict_types=1);
namespace Aeon\Calendar\Gregorian;
use Aeon\Calendar\Exception\InvalidArgumentException;
use Aeon\Calendar\Unit;
/**
* @implements \Iterator<DateTime>
*/
final class DateTimeIterator implements \Iterator
{
private DateTime $currentDate;
private DateTime $start;
private DateTime $end;
private Unit $timeUnit;
private int $key;
private bool $forward;
private bool $empty;
/**
* @throws InvalidArgumentException
*/
public function __construct(DateTime $start, DateTime $end, Unit $timeUnit)
{
$this->start = $start;
$this->end = $end;
$this->timeUnit = $timeUnit;
$this->currentDate = $start;
$this->key = 0;
$this->forward = $start->isBeforeOrEqualTo($end);
$this->empty = $start->isEqualTo($end);
if ($this->forward && $timeUnit->isNegative()) {
throw new InvalidArgumentException("Forward DateTimeIterator {$start->format('Y-m-d H:i:sP')}...{$end->format('Y-m-d H:i:sP')} requires positive TimeUnit");
}
if (!$this->forward && !$timeUnit->isNegative()) {
throw new InvalidArgumentException("Backward DateTimeIterator {$start->format('Y-m-d H:i:sP')}...{$end->format('Y-m-d H:i:sP')} requires negative TimeUnit");
}
}
public function isForward() : bool
{
return $this->forward;
}
public function unit() : Unit
{
return $this->timeUnit;
}
public function start() : DateTime
{
return $this->start;
}
public function end() : DateTime
{
return $this->end;
}
public function current() : DateTime
{
return $this->currentDate;
}
public function next() : void
{
$this->currentDate = $this->currentDate->add($this->timeUnit);
$this->key++;
}
public function hasNext() : bool
{
if ($this->forward) {
return !$this->current()->add($this->timeUnit)->isAfter($this->end);
}
return !$this->current()->add($this->timeUnit)->isBefore($this->end);
}
public function key() : int
{
return $this->key;
}
public function isFirst() : bool
{
return $this->key() === 0;
}
public function valid() : bool
{
if ($this->empty) {
return false;
}
if ($this->forward) {
return $this->currentDate->isBeforeOrEqualTo($this->end);
}
return $this->currentDate->isAfterOrEqualTo($this->end);
}
public function rewind() : void
{
$this->currentDate = $this->start;
$this->key = 0;
}
}